package com.attendance.www.hr.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.attendance.www.hr.beans.ApprovalRecordBean;
import com.attendance.www.hr.beans.AttendanceBean;
import com.attendance.www.hr.beans.HRParamBean;
import com.attendance.www.hr.beans.RequestApprovalBean;
import com.attendance.www.hr.beans.RequestApprovalPageBean;
import com.attendance.www.hr.beans.RequestApprovalParamBean;
import com.attendance.www.hr.beans.RequestApprovalSaveBean;
import com.attendance.www.hr.beans.RestVacationBean;
import com.attendance.www.hr.dao.mapper.ApprovalRecordMapper;
import com.attendance.www.hr.dao.mapper.AttendanceExtMapper;
import com.attendance.www.hr.dao.mapper.AttendanceMapper;
import com.attendance.www.hr.dao.mapper.AttendanceReportExtMapper;
import com.attendance.www.hr.dao.mapper.CorporationMapper;
import com.attendance.www.hr.dao.mapper.EmployeeCorporationMapper;
import com.attendance.www.hr.dao.mapper.EmployeeExtMapper;
import com.attendance.www.hr.dao.mapper.EmployeeMapper;
import com.attendance.www.hr.dao.mapper.EmployeeSchedulMapper;
import com.attendance.www.hr.dao.mapper.FurloughBalanceMapper;
import com.attendance.www.hr.dao.mapper.HRExtMapper;
import com.attendance.www.hr.dao.mapper.HrRequestApprovalExtMapper;
import com.attendance.www.hr.dao.mapper.LinkAddressMapper;
import com.attendance.www.hr.dao.mapper.PunchTimeMapper;
import com.attendance.www.hr.dao.mapper.RequestApprovalExtMapper;
import com.attendance.www.hr.dao.mapper.RequestMapper;
import com.attendance.www.hr.dao.mapper.RetroactiveMapper;
import com.attendance.www.hr.dao.mapper.SchedulDayMapper;
import com.attendance.www.hr.dao.mapper.SystemConfigureMapper;
import com.attendance.www.hr.dao.mapper.TaskMapper;
import com.attendance.www.hr.entitys.ApprovalRecord;
import com.attendance.www.hr.entitys.ApprovalRecordExample;
import com.attendance.www.hr.entitys.Attendance;
import com.attendance.www.hr.entitys.AttendanceExample;
import com.attendance.www.hr.entitys.Employee;
import com.attendance.www.hr.entitys.EmployeeCorporation;
import com.attendance.www.hr.entitys.EmployeeCorporationExample;
import com.attendance.www.hr.entitys.EmployeeSchedul;
import com.attendance.www.hr.entitys.EmployeeSchedulExample;
import com.attendance.www.hr.entitys.FurloughBalance;
import com.attendance.www.hr.entitys.FurloughBalanceExample;
import com.attendance.www.hr.entitys.LinkAddressExample;
import com.attendance.www.hr.entitys.PunchTime;
import com.attendance.www.hr.entitys.Request;
import com.attendance.www.hr.entitys.RequestExample;
import com.attendance.www.hr.entitys.Retroactive;
import com.attendance.www.hr.entitys.RetroactiveExample;
import com.attendance.www.hr.entitys.SchedulDayExample;
import com.attendance.www.hr.entitys.SchedulDayKey;
import com.attendance.www.hr.entitys.Task;
import com.attendance.www.hr.entitys.TaskExample;
import com.attendance.www.hr.service.IApprovalService;
import com.attendance.www.hr.service.IHRService;
import com.attendance.www.hr.service.IRestVacationService;
import com.attendance.www.hr.utils.TimeUtils;

@Service
public class HRServiceImpl implements IHRService {

	@Resource
	private AttendanceExtMapper attendanceExtDao;
	@Resource
	private HRExtMapper hrDao;
	@Resource
	private EmployeeCorporationMapper employeeCorporationDao;
	@Resource
	private EmployeeMapper employeeDao;
	@Resource
	private EmployeeExtMapper employeeExtDao;
	@Resource
	private RequestApprovalExtMapper requestApprovalExtDao;
	@Resource
	private RequestMapper requestDao;
	@Resource
	private ApprovalRecordMapper approvalRecordDao;
	@Resource
	private FurloughBalanceMapper furloughBalanceDao;
	@Resource
	private IRestVacationService restVacationService;
	@Resource
	private CorporationMapper corporationDao;
	@Resource
	private PunchTimeMapper punchTimeDao;
	@Resource
	private SchedulDayMapper schedulDayDao;
	@Resource
	private EmployeeSchedulMapper employeeSchedulDao;
	@Resource
	private RetroactiveMapper retroactiveDao;
	@Resource
	private AttendanceMapper attendanceDao;
	@Resource
	private HrRequestApprovalExtMapper HrRequestApprovalExtDao;
	@Resource
	private IApprovalService approvalService;
	@Resource
	private SystemConfigureMapper systemConfigureDao;
	@Resource
	private LinkAddressMapper linkAddressDao;
	@Resource
	private AttendanceReportExtMapper attendanceReportExtDao;
	@Resource
	private TaskMapper taskDao;
	
	
	/**
	 * 查询申请信息
	 */
	@Override
	public RequestApprovalPageBean getRequestList(HRParamBean paramBean,Integer employeeId, Integer startNum, Integer pageCount) {
		Map<Integer, EmployeeCorporation> employeeCorporationMap= new HashMap<Integer,EmployeeCorporation>();
		List<Integer> employeeIdList=null;

		//取出申请记录
		RequestApprovalPageBean requestApprovalPageBean = new RequestApprovalPageBean();
		List<RequestApprovalBean> requestApprovalBeanList=new ArrayList<RequestApprovalBean>();
		//等于空为管理员，不等于空为用户
		if(employeeId!=null){
			//取得HR管理的公司列表
			EmployeeCorporationExample employeeCorporationExample = new EmployeeCorporationExample();
			employeeCorporationExample.createCriteria()
			.andEmployeeIdEqualTo(employeeId)
			.andIsCorporationEqualTo(1);
			List<EmployeeCorporation> employeeCorporationList = employeeCorporationDao.selectByExample(employeeCorporationExample);
			if(employeeCorporationList==null || employeeCorporationList.size()==0){
				return null;
			}
			List<Integer> corporationIdList = new ArrayList<Integer>();
			for (EmployeeCorporation employeeCorporation : employeeCorporationList) {
				corporationIdList.add(employeeCorporation.getCorporationId());
				employeeCorporationMap.put(employeeCorporation.getCorporationId(), employeeCorporation);
			}
			
			AttendanceBean attendanceBean=new AttendanceBean();
			//查询用户下分配的公司员工
			employeeIdList = attendanceExtDao.getEmployeeByCorporation(attendanceBean, employeeId);
			if (employeeIdList.size() == 0) {
				requestApprovalPageBean.setRequestApprovalList(requestApprovalBeanList);
				requestApprovalPageBean.setPageTotal(0);
				return requestApprovalPageBean;
			}
		}

		RequestApprovalParamBean requestApprovalParamBean=new RequestApprovalParamBean();
		requestApprovalParamBean.setStartNum(startNum);
		requestApprovalParamBean.setPageCount(pageCount);
		requestApprovalParamBean.setStartDate(paramBean.getFromDate());
		requestApprovalParamBean.setEndDate(paramBean.getThruDate());
		requestApprovalParamBean.setCorporationList(paramBean.getCorporationList());
		requestApprovalParamBean.setDepartmentList(paramBean.getDepartmentList());
		requestApprovalParamBean.setEmployeeLevelList(paramBean.getEmployeeLevelList());
		requestApprovalParamBean.setApprovalState(paramBean.getApprovalState());
		requestApprovalParamBean.setHrApprovalState(paramBean.getHrApprovalState());
		requestApprovalParamBean.setRequestStartDayNumber(paramBean.getRequestStartDayNumber());
		requestApprovalParamBean.setRequestEndDayNumber(paramBean.getRequestEndDayNumber());
		requestApprovalParamBean.setEmployeeList(paramBean.getEmployeeList());
		requestApprovalParamBean.setEmployeeIdList(employeeIdList);
		//requestApprovalParamBean.setRequestEmployeeList(requestEmployeeList);
		requestApprovalParamBean.setRequestType(paramBean.getRequestType());
		requestApprovalParamBean.setRoleIdList(paramBean.getRoleIdList());
		requestApprovalParamBean.setRequestTypeList(paramBean.getRequestTypeList());
		
		requestApprovalPageBean = new RequestApprovalPageBean();
		requestApprovalBeanList=HrRequestApprovalExtDao.getHrRequestApprovalList(requestApprovalParamBean);
		for(int i=0;i<requestApprovalBeanList.size();i++){
			RequestApprovalBean requestApprovalBean=requestApprovalBeanList.get(i);
			if(employeeCorporationMap.containsKey(requestApprovalBean.getCorporationId())){
				EmployeeCorporation employeeCorporation=employeeCorporationMap.get(requestApprovalBean.getCorporationId());
				requestApprovalBeanList.get(i).setIsApproval(employeeCorporation.getIsApproval());
			}
		}
		
		requestApprovalPageBean.setRequestApprovalList(requestApprovalBeanList);
		requestApprovalPageBean.setPageTotal(HrRequestApprovalExtDao.countHrRequestApprovalList(requestApprovalParamBean));
		return requestApprovalPageBean;
	}

	/**
	 * HR驳回申请
	 */
	@Override
	public void getRejectRequest(RequestApprovalSaveBean requestApprovalSaveBean,Integer employeeId) {
		//取出页面选择的申请信息
		RequestExample requestExample = new RequestExample();
		requestExample.createCriteria().andRequestIdIn(requestApprovalSaveBean.getRequestIdList());
		List<Request> requestList = requestDao.selectByExample(requestExample);

		for (Request request : requestList) {
			//取审批记录
			ApprovalRecordExample approvalExample = new ApprovalRecordExample();
			ApprovalRecordExample.Criteria criteria = approvalExample.createCriteria();
			criteria.andRequestIdEqualTo(request.getRequestId());
			approvalExample.setOrderByClause("sep desc");
			
			List<ApprovalRecord> approvalRecordList = approvalRecordDao.selectByExample(approvalExample);
			Integer maxSeq = 0;
			if(approvalRecordList!=null && approvalRecordList.size()>0){
				maxSeq = approvalRecordList.get(0).getSep();
			}
			ApprovalRecord approvalRecord = new ApprovalRecord();
			Integer requestType=request.getRequestType();
			// 如果已经审批通过了，修改假期余额表
			if (request.getApprovalState() == 2) {
				if (requestType==0||requestType==1||requestType==7) {
					//取得年份
					Calendar calendar = Calendar.getInstance();
					calendar.setTime(request.getStartDate());
					Integer thisYear = calendar.get(Calendar.YEAR);
					
					FurloughBalance furloughBalance = new FurloughBalance();
					RestVacationBean restVacationBean = new RestVacationBean();
					restVacationBean.setStartDate(request.getStartDate());
					if (request.getRequestType() == 7) {
						restVacationBean.setFurloughType(0);
						restVacationBean = restVacationService.getRestVacationByType(restVacationBean, request.getEmployeeId());
					} 
					/*else {
						restVacationBean.setFurloughType(request.getRequestType());
						restVacationBean = restVacationService.getRestVacationByType(restVacationBean,
								request.getEmployeeId());
					}*/
					else if(request.getRequestType()==0){
						restVacationBean.setFurloughType(request.getRequestType());
						restVacationBean = restVacationService.getRestVacationByType(restVacationBean,request.getEmployeeId());
					}else if(request.getRequestType()==1){
						restVacationBean.setFurloughType(request.getRequestType());
						restVacationBean = restVacationService.getLastYearYearFurlough(restVacationBean, request.getEmployeeId());
					}
					
					
					if (request.getHours() == null) {
						if (request.getRequestType() != 7) {
							
							furloughBalance.setBalanceHoursDay(
									restVacationBean.getRestVacation().add(new BigDecimal(request.getDayNumber())));
						} else {
							furloughBalance.setBalanceHoursDay(
									restVacationBean.getRestVacation().subtract(new BigDecimal(request.getDayNumber())));
						}
					} else {//只会有hours，按天的不操作余额表
						if (request.getRequestType() != 7) {
//							furloughBalance.setBalanceHoursDay(restVacationBean.getRestVacation().add(request.getHours()));
							if(request.getRequestType()==0){
								furloughBalance.setBalanceHoursDay(restVacationBean.getRealRestVacation().add(request.getHours()));
							}else if(request.getRequestType()==1){
								Integer reportYear=request.getReportYear();
								if (reportYear.equals(thisYear)) {//同一年
									furloughBalance.setBalanceHoursDay(restVacationBean.getRealRestVacation().add(request.getHours()));
								} else {//去年
									furloughBalance.setBalanceHoursDay(restVacationBean.getRealLastYearRestVacation().add(request.getHours()));
								}
							}
						} else {
							furloughBalance.setBalanceHoursDay(restVacationBean.getRestVacation().subtract(request.getHours()));
						}
						
					}
					FurloughBalanceExample furloughBalanceExample = new FurloughBalanceExample();
					FurloughBalanceExample.Criteria furloughBalanceCriteria = furloughBalanceExample.createCriteria();
					furloughBalanceCriteria.andEmployeeIdEqualTo(request.getEmployeeId());
					furloughBalanceCriteria.andFurloughBalanceTypeEqualTo(request.getRequestType());
					if(request.getRequestType()==7){
						furloughBalanceCriteria.andFurloughBalanceTypeEqualTo(0);
					}else{
						furloughBalanceCriteria.andFurloughBalanceTypeEqualTo(request.getRequestType());
					}
					if(request.getRequestType()==1&&request.getStartDate()!=null) {
				        int year = request.getReportYear();
				        furloughBalance.setYear(year+"");
						furloughBalanceCriteria.andYearEqualTo(year+"");
					}
					furloughBalance.setUpdateTime(new Date());
					furloughBalanceDao.updateByExampleSelective(furloughBalance, furloughBalanceExample);
				}
			}
			//审批驳回，添加审批记录和修改申请表状态
			approvalRecord.setRequestId(request.getRequestId());
			approvalRecord.setApprovalDate(new Date());
			approvalRecord.setEmployeeId(employeeId);
			approvalRecord.setIsApprove(3);
			approvalRecord.setSep(maxSeq+1);
			approvalRecord.setApprovalDescription(requestApprovalSaveBean.getDescription());
			approvalRecord.setCreateTime(new Date());
			approvalRecord.setUpdateTime(new Date());
			approvalRecordDao.insertSelective(approvalRecord);
			request.setRequestId(request.getRequestId());
			request.setApprovalState(3);
			request.setUpdateTime(null);//设置更新时间
			requestDao.updateByPrimaryKeySelective(request);
			
			if (request.getApprovalState() == 2) {
				//重新计算考勤状态
				if(request.getRequestType() == 0 ||request.getRequestType() == 1 ||request.getRequestType() == 2 ||request.getRequestType() == 3 
						||request.getRequestType() == 4 || request.getRequestType() == 5 || request.getRequestType() == 6 ||request.getRequestType() == 8 
						||request.getRequestType() == 9 ||request.getRequestType() == 11 ||request.getRequestType() == 12 ||request.getRequestType() == 13){
//					resetAttendance(request.getStartDate(),request.getEndDate(),request.getEmployeeId());
					List<Integer> employeeIdList = new ArrayList<>();
					employeeIdList.add(request.getEmployeeId());
					approvalService.resetAttendance(request.getStartDate(),request.getEndDate(),employeeIdList);
				}
			}
		}
	}
	
	/*
	 * 更新考勤状态 
	 * @param curDate
	 * @param employeeId
	 */
	public void resetAttendance(Date startDate,Date endDate, Integer employeeId){
		//取出包含当天的申请（不包含补签和加班申请）
		List<Integer> requestTypeList = new ArrayList<Integer>(); 
		requestTypeList.add(0);
		requestTypeList.add(1);
		requestTypeList.add(2);
		requestTypeList.add(3);
		requestTypeList.add(4);
		requestTypeList.add(5);
		requestTypeList.add(6);
		requestTypeList.add(8);
		requestTypeList.add(9);
		requestTypeList.add(11);
		requestTypeList.add(12);
		requestTypeList.add(13);
		
		//控制循环用的
		Date curDate = DateUtils.addDays(new Date(startDate.getTime()), -1);
		while (curDate.compareTo(endDate) < 0) {
			curDate = DateUtils.addDays(curDate, 1);
			RequestExample example = new RequestExample();
			example.createCriteria().andStartDateLessThanOrEqualTo(curDate).andEndDateGreaterThanOrEqualTo(curDate).andEmployeeIdEqualTo(employeeId).andRequestTypeIn(requestTypeList);
			List<Request> requestList = requestDao.selectByExample(example);
			
			//取得人员的排班时间
			EmployeeSchedulExample employeeSchedulExample = new EmployeeSchedulExample();
			employeeSchedulExample.or().andEmployeeIdEqualTo(employeeId).andFromDateLessThanOrEqualTo(curDate).andThruDateGreaterThanOrEqualTo(curDate);
			employeeSchedulExample.or().andEmployeeIdEqualTo(employeeId).andFromDateLessThanOrEqualTo(curDate).andThruDateIsNull();
			employeeSchedulExample.setOrderByClause("from_date desc");
			List<EmployeeSchedul> employeeSchedulList = employeeSchedulDao.selectByExample(employeeSchedulExample);
			if(employeeSchedulList==null || employeeSchedulList.size()==0){
				//未找到排班信息,后续不处理
				return;
			}
			
			//考虑休息日的情况
			SchedulDayExample sdExample = new SchedulDayExample();
			sdExample.createCriteria().andSdDateEqualTo(curDate).andSwIdEqualTo(employeeSchedulList.get(0).getSwId());
			List<SchedulDayKey> schedulDayList = schedulDayDao.selectByExample(sdExample);
			//如果没查到数据，证明不上班。
			if(schedulDayList == null || schedulDayList.size()==0){
				return;
			}
			//用于存储计算的时间段
			List<String[]>  datatimeList = new ArrayList<String[]>();
			
			//取得签到原始数据
			AttendanceExample attendanceExample = new AttendanceExample();
			AttendanceExample.Criteria attendanceCriteria = attendanceExample.createCriteria();
			attendanceCriteria.andAttendanceDateEqualTo(curDate);
			attendanceCriteria.andEmployeeIdEqualTo(employeeId);
			List<Attendance> attendanceList = attendanceDao.selectByExample(attendanceExample);
			if(attendanceList == null || attendanceList.size()==0){
				return ;
			}
			Attendance att = attendanceList.get(0);
			//取得申请通过的补签
			RetroactiveExample retroactiveExample = new RetroactiveExample();
			retroactiveExample.createCriteria().andAttendanceIdEqualTo(attendanceList.get(0).getAttendanceId()).andApprovalStateEqualTo(2);
			List<Retroactive> retroactiveList = retroactiveDao.selectByExample(retroactiveExample);
			String stime="";
			String etime="";
			if(retroactiveList != null && retroactiveList.size()>0){
				stime=att.getOriginalStartTime();
				etime=att.getOriginalEndTime();
				for (Retroactive retroactive : retroactiveList) {
					if(!StringUtils.isEmpty(retroactive.getStartTime())){
						if(!StringUtils.isEmpty(att.getOriginalStartTime())){
							if(TimeUtils.compareTime(retroactive.getStartTime(), att.getOriginalStartTime())<0){
								stime = retroactive.getStartTime();
							}
						}else{
							stime = retroactive.getStartTime();
						}
					}
					if(!StringUtils.isEmpty(retroactive.getEndTime())){
						if(!StringUtils.isEmpty(att.getOriginalEndTime())){
							if(TimeUtils.compareTime(retroactive.getEndTime(), att.getOriginalEndTime())>0){
								etime = retroactive.getEndTime();
							}
						}else{
							etime = retroactive.getEndTime();
						}
					}
				}
			}
			if(!StringUtils.isEmpty(stime) && !StringUtils.isEmpty(etime)){
				datatimeList.add(new String[]{stime,etime});
			}
			//取得打卡时间配置记录
			PunchTime punchTime = punchTimeDao.selectByPrimaryKey(employeeSchedulList.get(0).getPunchTimeId());
			
			//取得应出勤时长
			Integer punchMinutes = TimeUtils.differMinutes(punchTime.getStartFromTime(), punchTime.getEndFromTime());
			
			for (Request request : requestList) {
				if(request.getStartDate().compareTo(curDate)==0 && request.getEndDate().compareTo(curDate)==0){
					//申请一天内的情况
					datatimeList.add(new String[]{request.getStartTime(),request.getEndTime()});
				}else if(request.getStartDate().compareTo(curDate)==0 && request.getEndDate().compareTo(curDate)>0){
					//申请跨天第一天内的情况
					datatimeList.add(new String[]{request.getStartTime(),request.getStartToTime()});
				}else if(request.getStartDate().compareTo(curDate)<0 && request.getEndDate().compareTo(curDate)==0){
					//申请跨天最后一天内的情况
					datatimeList.add(new String[]{punchTime.getStartFromTime(),request.getStartToTime()});
				}else{
					//请假中间天
					datatimeList.add(new String[]{punchTime.getStartFromTime(),punchTime.getEndFromTime()});
				}
			}
			
			stime = "";
			etime = "";
			for (String[] datetimes : datatimeList) {
				if(stime == ""){
					stime = datetimes[0];
					etime = datetimes[1];
				}
				for (String[] dtimes : datatimeList) {
					if(TimeUtils.compareTime(stime, dtimes[0])>0 && TimeUtils.compareTime(stime, dtimes[1])<=0){
						stime = dtimes[0];
					}
					if(TimeUtils.compareTime(etime, dtimes[1])<0 && TimeUtils.compareTime(etime, dtimes[0])>=0){
						etime = dtimes[1];
					}
				}
			}
			
			//计算有效时间点
			if(TimeUtils.compareTime(punchTime.getStartFromTime(), stime)>0){
				stime = punchTime.getStartFromTime();
			}
			if(TimeUtils.compareTime(punchTime.getEndToTime(), etime)<0){
				etime = punchTime.getEndToTime();
			}
			
			//取得出勤时长
			Integer dayMinutes = TimeUtils.differMinutes(stime,etime);
			Integer startStatus = 1;
			Integer endStatus = 1;
			//出勤时间不够
			if(dayMinutes < punchMinutes){
				if(TimeUtils.compareTime(punchTime.getStartToTime(), stime)<0){
					if(TimeUtils.differMinutes(punchTime.getStartToTime(), stime) > punchTime.getStartInterval()){
						// 早旷工
						startStatus = 5;
					}else{
						// 早迟到
						startStatus = 2;
					}
				}
				if(TimeUtils.compareTime(punchTime.getEndFromTime(), etime)>0){
					if(TimeUtils.differMinutes(etime,punchTime.getEndFromTime()) > punchTime.getEndInterval()){
						// 晚 旷工
						endStatus = 5;
					}else{
						// 晚 早退
						endStatus = 3;
					}
				}
			}else{
				//正常
			}
			
			if(startStatus == 5 || endStatus == 5){
				//旷工
				att.setAttendanceState(5);
			}else if (startStatus == 2 && endStatus == 1){
				//迟到
				att.setAttendanceState(2);
			}else if (startStatus == 1 && endStatus == 3){
				//早退
				att.setAttendanceState(3);
			}else if (startStatus == 2 && endStatus == 3){
				//迟到并早退
				att.setAttendanceState(6);
			}else{
				//正常
				att.setAttendanceState(1);
			}
			att.setStartTime(stime);
			att.setEndTime(etime);
			att.setUpdateTime(new Date());
			attendanceDao.updateByPrimaryKeySelective(att);
		}
	}

	/**
	 * HR驳回补签
	 */
	@Override
	public boolean saveRejectRetroactive(RequestApprovalSaveBean requestApprovalSaveBean, Integer employeeId) {
		List<Integer> idList = requestApprovalSaveBean.getRequestIdList();//补签id List
		RetroactiveExample retroactiveExample = new RetroactiveExample();
		retroactiveExample.createCriteria().andRetroactiveIdIn(idList);
		List<Retroactive> retroactivelist = retroactiveDao.selectByExample(retroactiveExample);
		//更新补签记录表
		Retroactive retro = new Retroactive();
		retro.setApprovalState(3);//审批拒绝 3
		retroactiveDao.updateByExampleSelective(retro, retroactiveExample);
		
		//更新审批记录表
		for (Retroactive retroactive : retroactivelist) {
			//取补签审批人信息List (邮件提醒)
			List<ApprovalRecordBean> arList = approvalService.getApprovalRecordById(retroactive.getRetroactiveId());
			//取审批记录
			ApprovalRecordExample approvalExample = new ApprovalRecordExample();
			ApprovalRecordExample.Criteria criteria = approvalExample.createCriteria();
			criteria.andRetroactiveIdEqualTo(retroactive.getRetroactiveId());
			approvalExample.setOrderByClause("sep desc");
			List<ApprovalRecord> approvalRecordList = approvalRecordDao.selectByExample(approvalExample);
			Integer maxSeq = 0;
			if(approvalRecordList!=null && approvalRecordList.size()>0){
				if(approvalRecordList.get(0).getSep()!=null) {
					maxSeq = approvalRecordList.get(0).getSep();
				}
			}
			//修改考勤记录 --zx
			Attendance attendance=attendanceDao.selectByPrimaryKey(retroactive.getAttendanceId());
			attendance.setIsRepaired(3);//补签失败
			attendance.setIsApprovaled(3);//审批拒绝
			attendanceDao.updateByPrimaryKeySelective(attendance);
			
			//审批驳回，添加审批(驳回)记录
			ApprovalRecord approvalRecord = new ApprovalRecord();
			approvalRecord.setRetroactiveId(retroactive.getRetroactiveId());
			approvalRecord.setApprovalDate(new Date());
			approvalRecord.setEmployeeId(employeeId);
			approvalRecord.setIsApprove(3);
			approvalRecord.setSep(maxSeq+1);
			approvalRecord.setApprovalDescription(requestApprovalSaveBean.getDescription());
			int record = approvalRecordDao.insertSelective(approvalRecord);
			if (record <= 0) {
				return false;
			}
			
			//重新计算考勤状态
			List<Integer> employeeIdList = new ArrayList<>();
			employeeIdList.add(retroactive.getEmployeeId());
			approvalService.resetAttendance(attendance.getAttendanceDate(), attendance.getAttendanceDate(), employeeIdList);

			//查询HRBP的姓名
			Employee empHRBP = employeeDao.selectByPrimaryKey(employeeId);
			
			//删除链接linkAddress
			LinkAddressExample laExample = new LinkAddressExample();
			laExample.createCriteria().andRetroactiveIdEqualTo(retroactive.getRetroactiveId());
			linkAddressDao.deleteByExample(laExample);
			
			//插入任务表数据
			approvalService.insertTaskByParam(attendance.getAttendanceDate(), attendance.getEmployeeId());
			
			//提醒审批人
			String textPart ="员工：" + employeeDao.selectByPrimaryKey(retroactive.getEmployeeId()).getChineseName()+"<br>"; 
			//提醒申请人
			textPart = textPart+"补签申请被HRBP："+empHRBP.getChineseName()+"驳回";
			//现在规则是N+1,所以用foreach
			for (ApprovalRecordBean approvalRecordBean : arList) {
				String ids = approvalRecordBean.getApproverIds();
				if (ids!=null) {
					String[] strIds=ids.split(",");
					for (int i = 0; i < strIds.length; i++) {
						approvalService.sendEmailByReject(Integer.parseInt(strIds[i]), textPart,requestApprovalSaveBean.getDescription());
					}
				} else {//如果ids为null，就给让审批通过的审批人发邮件
					if(approvalRecordBean.getEmployeeId()!=null) {
						approvalService.sendEmailByReject(approvalRecordBean.getEmployeeId(), textPart,requestApprovalSaveBean.getDescription());
					}
				}
			}
			textPart = "您的补签申请被HRBP："+empHRBP.getChineseName()+"驳回";
			approvalService.sendEmailByReject(retroactive.getEmployeeId(), textPart,requestApprovalSaveBean.getDescription());
		}
		return true;
	}
}
